package cn.com.isfree.tio;

import java.util.concurrent.atomic.AtomicLong;

import org.tio.server.AioServer;
import org.tio.server.ServerGroupContext;
import org.tio.server.intf.ServerAioHandler;
import org.tio.server.intf.ServerAioListener;
import cn.com.isfree.tio.server.ShowcaseServerAioHandler;
import cn.com.isfree.tio.server.ShowcaseServerAioListener;

public class TioUil {
	/**
	 * 同步发送并发控制使用
	 */
	private static AtomicLong synSeqAtomicLong = new AtomicLong();

	/***服务端****/
	public static ServerGroupContext serverGroupContext;
	
	private static AioServer aioServer;

	public static boolean initTio(String serverIp, int serverPort) {
		try {
			ServerAioHandler aioHandler = new ShowcaseServerAioHandler();
			ServerAioListener aioListener = new ShowcaseServerAioListener();
			serverGroupContext = new ServerGroupContext(aioHandler, aioListener);
			aioServer = new AioServer(serverGroupContext); //可以为空
			aioServer.start(serverIp, serverPort);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static boolean serverStop(){
		boolean s = false;
		if(aioServer!=null) {
			s = aioServer.stop();
			if(s) {
				serverGroupContext = null;
				serverGroupContext = null;
			}
		}
		return s;
	}

	/**
	 * 同步自增长序列号
	 * @return
	 */
	public static int getSynSeqAtomicLong() {
		try {
			int inc = (int) synSeqAtomicLong.incrementAndGet();
			if(inc<1) {
				synSeqAtomicLong = new AtomicLong();
				inc = (int) synSeqAtomicLong.incrementAndGet();
			}
			return inc;
		}catch (Exception e) {
			//超出int类型后直接从新统计AtomicLong
			e.printStackTrace();
			synSeqAtomicLong = new AtomicLong();
			return (int) synSeqAtomicLong.incrementAndGet();
		}
		
	}
}
